from django.shortcuts import render, redirect, HttpResponse
from django.views import View

from user import forms
from user.models import Users
from utils.code import check_code


# Create your views here.
class RegisterView(View):

    def get(self, request):
        return render(request, 'user/user_register.html', {'form': forms.RegAndLogForm()})

    def post(self, request):
        form = forms.RegAndLogForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get('name')
            password = form.cleaned_data.get('password')
            try:
                user = Users.objects.get_or_create(name=name, password=password)
                print(user)
            except Exception as e:
                print(e)
            return redirect('user:login')
        return render(request, 'user/user_register.html', {
            'form': form,
        })


class LoginView(View):

    def get(self, request):
        form = forms.RegAndLogForm()
        return render(request, 'user/user_login.html', context={
            'form': form
        })

    def post(self, request):

        form = forms.RegAndLogForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get("name")
            passwd = form.cleaned_data.get("password")
            user_input_code = form.cleaned_data.pop('code')
            image_code = request.session.get('image_code')
            if image_code:
                if image_code.upper() != user_input_code.upper():
                    form.add_error('code', '验证码错误')
                    return render(request, 'user/user_login.html', context={
                        'form': form,
                    })
            else:
                form.add_error('code', '验证码已过期')
                return render(request, 'user/user_login.html', context={
                    'form': form,
                })
            # 验证码校验


            print(name, passwd)
            user = Users.objects.filter(name=name, password=passwd).first()
            print(user)
            if user:
                request.session['info'] = {
                    'name': user.name,
                    'password': user.password
                }
                request.session.set_expiry(60*60*24*7)
                return render(request, 'csdn_django/csdn.html', context={
                    'form': form,
                    'success': '登录成功'
                })
            else:
                form.add_error('name', '用户名或密码错误')
                form.add_error('password', '用户名或密码错误')
        return render(request, 'user/user_login.html', context={
            'form': form,
        })


def logout(request):
    """登出功能"""
    request.session.flush()
    return redirect('csdn')


from io import BytesIO


# 生成图片验证码
def image_code(request):
    img, code_str = check_code()
    # 写到session中进行校验
    request.session['image_code'] = code_str
    # 设置session过期时间
    request.session.set_expiry(60)
    stream = BytesIO()
    img.save(stream, 'png')
    stream.getvalue()
    return HttpResponse(stream.getvalue())
